'''
Created on Apr 23, 2013

@author: alex
'''
import socket, thread, Handler, time, threading, CacheProxy, select
class Server(threading.Thread):
    def __init__(self, txtLabel, cacheActive = False, cacheSize = 1048576, deleteTime = 60, lockTimeout = 600):
        super(Server, self).__init__()
        self.cacheActive = cacheActive
        self.cacheSize = cacheSize
        self.deleteTime = float(deleteTime)
        if cacheActive:
            self.cache = CacheProxy.CacheProxy(txtLabel, cacheSize, lockTimeout)
        else:
            self.cache = None
        self._stop = threading.Event()
        self.clientSocket = socket.socket(socket.AF_INET) #change for custom transport-layer
        self.clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.clientSocket.bind(('172.23.14.155', 9000))      
    def run(self):
        self.clientSocket.listen(0)
        while 1:
            if self.stopped():
                print 'stopping'
                break
            socketList = [self.clientSocket]
            readable, writable, error = select.select(socketList, [], [], 5)
            thread.start_new_thread(self.kill, (float(self.deleteTime), ))
            for s in readable:
                thread.start_new_thread(Handler.Handler, (s.accept(), self.cacheActive, self.cache)) #uncomment for multi-threaded
        #handle = Handler.Handler(self.clientSocket.accept())
        time .sleep(10)        
        self.clientSocket.close()
    def stop(self):
        self._stop.set()
    def stopped(self):
        return self._stop.is_set()
    def kill(self, t):
        time.sleep(t)
        self.cache.kill()
        
if __name__ == '__main__':
    proxy = Server()
    proxy.run()